//
//  SProtocolMediator.m
//  Pods
//
//  Created by 王剑飞 on 2017/5/16.
//
//

#import "SProtocolMediator.h"

static SProtocolMediator *instance = nil;

@interface SProtocolMediator ()

@property (nonatomic, strong) NSMutableDictionary *impCache;

@property (nonatomic, strong) dispatch_semaphore_t lock;

@end

@implementation SProtocolMediator

- (instancetype)init {
    self = [super init];
    if (self) {
        self.impCache = [NSMutableDictionary dictionaryWithCapacity:0];
        self.lock = dispatch_semaphore_create(1);
    }
    return self;
}

+ (instancetype)shareInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[SProtocolMediator alloc] init];
    });
    return instance;
}

- (id)impForProtocol:(Protocol *)protocol {
    id obj = nil;
    dispatch_semaphore_wait(self.lock, DISPATCH_TIME_FOREVER);
    obj = [self.impCache objectForKey:NSStringFromProtocol(protocol)];
    dispatch_semaphore_signal(self.lock);
    return obj;
}

- (void)setImp:(id)imp forProtocol:(Protocol *)protocol {
    dispatch_semaphore_wait(self.lock, DISPATCH_TIME_FOREVER);
    [self.impCache setObject:imp forKey:NSStringFromProtocol(protocol)];
    dispatch_semaphore_signal(self.lock);
}

@end

id impForProtocol(Protocol *protocol) {
    return [[SProtocolMediator shareInstance] impForProtocol:protocol];
}
